package com.rgs.base.core.util.excel;


import com.rgs.base.core.function.CheckFunction;
import com.rgs.base.core.page.IPageRequestModel;
import com.rgs.base.core.page.IPageResponseModel;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;

/**
 * @author Ren Gaoshuai
 * @date 2022-03-08 15:45
 **/

public class ExcelWriteIterator<T> implements Iterator<List<T>> {

    private IPageRequestModel pageRequestModel;
    private IPageResponseModel pageResponseModel;

    private CheckFunction<IPageRequestModel, IPageResponseModel> readNextPage;

    private Function<Object, List<T>> converter = (obj) -> (List<T>) obj;

    private static final Integer DEF_ROWS = 100;

    public ExcelWriteIterator(IPageRequestModel pageRequestModel,
                              CheckFunction<IPageRequestModel, IPageResponseModel> readNextPage) {
        this.pageRequestModel = pageRequestModel;
        if (Objects.isNull(this.pageRequestModel.getPerPage())) {
            this.pageRequestModel.setPerPage(DEF_ROWS);
        }
        this.pageRequestModel.setPage(1);
        this.readNextPage = readNextPage;
    }

    //    String orderBy,
    public ExcelWriteIterator(IPageRequestModel pageRequestModel,
                              CheckFunction<IPageRequestModel, IPageResponseModel> readNextPage,
                              Function<Object, List<T>> converter) {
        this(pageRequestModel, readNextPage);
        this.converter = converter;
    }

//    public ExcelWriteIterator(String orderBy,
//                              Function<IPageRequestModel, IPageResponseModel> readNextPage) {
//        this(new PageDefRequestModel(DEF_ROWS, 1, orderBy), readNextPage);
//    }


    @Override
    public boolean hasNext() {
        if (Thread.currentThread().isInterrupted()) {
            return false;
        } else if (this.pageResponseModel == null) {
            return true;
        } else if (this.pageResponseModel.getPage() <
                this.pageResponseModel.getCount()) {
            return true;
        }
        return false;
    }

    @Override
    public List<T> next() {

        try {
            this.pageResponseModel = this.readNextPage.apply(this.pageRequestModel);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<T> tList = converter.apply(this.pageResponseModel.getDataList());
        this.pageRequestModel.setPage(this.pageRequestModel.getPage() + 1);
        return tList;
    }
}
